'use strict';
const mysql=require('mysql');
const koa=require('koa');
const router=require('koa-router')();
const koaBody=require('koa-body')
const https=require('https');
const http=require('http')
var path=require('path');
const fs=require('fs');
const enforceHttps=require('koa-sslify').default;

const ser=new koa();
var pool=mysql.createPool({
    user:'root',
    password:'*****',
    host:'你的地址',
    port:'端口',
    database:'https',
});

//转换为https
ser.use(enforceHttps());

ser.use(async (ctx,next)=>{
    console.log(ctx.request.url);
    await next();
})

router.get('/',async (ctx,next)=>{
    ctx.response.type='text/html';
    ctx.response.body=fs.readFileSync('./test/index.html');
})
router.get('/index.html',async (ctx,next)=>{
    ctx.response.type='text/html';
    ctx.response.body=fs.readFileSync('./test/index.html');
})
router.get('/resource/photo1.jpg',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./resource/photo1.jpg');
})
router.get('/resource/44.jpg',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./resource/44.jpg');
})
router.get('/resource/photo2.jpg',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./resource/photo2.jpg');
})
router.get('/photo.png',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./test/photo.png');
})
router.get('/css/interface.css',async (ctx,next)=>{
    ctx.response.type='text/css';
    ctx.response.body=fs.readFileSync('./test/css/interface.css');
})
router.get('/js/interface.js',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./test/js/interface.js');
})
//备案图标
router.get('/b.png',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./test/b.png');
})
//注册页面
router.get('/register.html',async (ctx,next)=>{
    ctx.response.type='text/html';
    ctx.response.body=fs.readFileSync('./test/register.html');
})
router.get('/resource/2233.jpg',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./resource/2233.jpg');
})
router.get('/css/register.css',async (ctx,next)=>{
    ctx.response.type='text/css'
    ctx.response.body=fs.readFileSync('./test/css/register.css');
})
router.get('/js/register.js',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./test/js/register.js');
})
router.get('/login.html',async (ctx,next)=>{
    ctx.response.type='text/html';
    ctx.response.body=fs.readFileSync('./test/login.html');
})
router.get('/css/login.css',async (ctx,next)=>{
    ctx.response.type='text/css';
    ctx.response.body=fs.readFileSync('./test/css/login.css');
})
router.get('/js/login.js',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./test/js/login.js');
})
//返回视频页面
router.get('/video.html',async (ctx,next)=>{
    ctx.response.type='text/html';
    ctx.response.body=fs.readFileSync('./test/video.html');
})
router.get('/css/video.css',async (ctx,next)=>{
    ctx.response.type='text/css';
    ctx.response.body=fs.readFileSync('./test/css/video.css');
})
router.get('/js/video.js',async (ctx,next)=>{
    ctx.response.body=fs.readFileSync('./test/js/video.js');
})
//返回视频数据  code为1表示暂无视频
router.get('/video',async (ctx,next)=>{
    var path=await query('select * from video',[]);
    var temp=[];
    for(let i of path){
        temp.push('/video/'+i['filename'])
    }
    console.log(temp)
    ctx.response.body=temp;
})
//解析post请求
ser.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 1000*1024*1024
    }
}))

//保存上传视频数据
router.post('/upload',async (ctx,next)=>{
    if(path.extname(ctx.request.files.file.name)!=='.mp4'){
        ctx.response.body='<script>alert("只能上传MP4文件");location.href="index.html"</script>'
        return;
    }
    let result=await query('select * from video where filename=?',[ctx.request.files.file.name])
    if(result.length!==0){
        console.log(result.length)
        ctx.response.body='<script>alert("该文件名已存在，请更改文件名重试");location.href="index.html"</script>'
        return;
    }
    //query('insert into video(filename) values(?)',[ctx.request.files.file.name]);
    let reader=fs.createReadStream(ctx.request.files.file.path);
    let writer=fs.createWriteStream('./test/video/'+ctx.request.files.file.name);
    reader.pipe(writer);
    ctx.response.body='<script>alert("文件上传成功!");location.href="index.html"</script>'
})

//返回弹幕信息
router.post('/getbarrage',async (ctx,next)=>{
    console.log(ctx.request.body.path)
    let data=await query('select time,data from barrage where video=?',[ctx.request.body.path]);
    ctx.response.body=data
})
//保存弹幕数据
router.post('/barrage',async (ctx,next)=>{
    var data=ctx.request.body['barrage'].split(' ');
    pool.getConnection((err,con)=>{
        if(err){
            throw err;
        }
        con.query('insert ignore into barrage(video,time,data) values(?,?,?)',[ctx.request.body.path,data[0],data[1]],(err,result)=>{
            if(err){
                throw err;
            }
        });
        con.release();
    })
    if(getCookie(ctx,'token')){
        pool.getConnection((err,con)=>{
            if(err){
                throw err;
            }
            con.query('update userdata set allexp=allexp+1 where nick=?',[getCookie(ctx,'token')],(err,result)=>{
                if(err){
                    throw err;
                }
            })
            con.release();
        })  
    }
    ctx.response.body={'code':1}
})
//返回用户信息
router.get('/test',async (ctx,next)=>{
    let data=await query('select * from userdata where nick=?',[getCookie(ctx,'token')]);
    let temp={'code':1,'nick':data[0]['nick'],'lv':data[0]['lv'],'allexp':data[0]['allexp'],'coin':data[0]['coin'],'follow':data[0]['follow'],'fan':data[0]['fan']}
    ctx.response.body=JSON.stringify(temp);
})

//注册
router.post('/server',async (ctx,next)=>{
    let data=await query('select username from user where username=?',[ctx.request.body.username]);
    console.log(data);
    if(data.length===0){
        pool.getConnection((err,con)=>{
            if(err){
                throw err;
            }
            con.query('insert into user(username,password) values(?,?)',[ctx.request.body.username,ctx.request.body.password],(err,result)=>{
                if(err){
                    console.log(err.message);
                    throw err;
                }
            })
            con.query('insert into userdata(nick,lv,allexp,coin,follow,fan) values(?,?,?,?,?,?)',[ctx.request.body.username,1,0,0,0,0,0],(err,result)=>{
                if(err){
                    throw err;
                }
            })
            con.release();
        })
        ctx.response.body=JSON.stringify({'code':1});
    }else{
        ctx.response.body=JSON.stringify({'code':2,'msg':'账号已存在'});
    }
})

//登录
router.post('/login',async (ctx,next)=>{
    let data=await query('select username,password from user where username=? and password=?',[ctx.request.body.username,ctx.request.body.password]);
    if(data.length!==0){
        ctx.response.set('Set-Cookie','token='+ctx.request.body.username+';path=/');
        ctx.response.body=JSON.stringify({'code':1});
    }      
    else
        ctx.response.body=JSON.stringify({'code':2,'msg':'账号或密码错误'});  
})

//登出
router.get('/account/logout',async (ctx,next)=>{
    var oDate=new Date();
    oDate.setDate(oDate.getDate()-7);
    let cook='token='+ctx.request.headers['cookie'].substring(6)+';expires='+oDate.toGMTString()+';path=/';
    ctx.response.set('Set-Cookie',cook);
    ctx.response.body=JSON.stringify({'code':1});
})

ser.use(router.routes());

var options={
    key:fs.readFileSync('***'),
    cert:fs.readFileSync('***')
}

https.createServer(options,ser.callback()).listen(443);
http.createServer(ser.callback()).listen(80);

console.log('Listen...');
//同步操作mysql
function query( sql, values ) {
    return new Promise(( resolve, reject ) => {
        pool.getConnection((err,con)=>{
            if(err){
                reject(err);
            }
            con.query(sql,values,(err,result)=>{
                if(err){
                    reject(err);
                }
                resolve(result);
            })
            con.release();
        })   
    })
}

//获取cookie
function getCookie(ctx,key) {
    var name = key + "=";
    var ca = ctx.request.headers['cookie'].split('; ');
    for(var i=0; i<ca.length; i++) 
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}